package com.shuma.shopmanage.security.interceptor;

import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.shuma.shopmanage.common.exception.ShopManageException;
import com.shuma.shopmanage.common.helper.JwtHelper;
import com.shuma.shopmanage.common.model.LoginUser;
import com.shuma.shopmanage.common.result.ResultCodeEnum;
import com.shuma.shopmanage.security.SecurityContextHolder;
import com.shuma.shopmanage.security.annotation.RequireRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Arrays;

/**
 * @author wp
 * @data 2023/10/22
 */
@Component
@Slf4j
public class HandleInterceptor implements AsyncHandlerInterceptor
{



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }
        String token = request.getHeader("token");
        LoginUser loginUser = JwtHelper.getLoginUser(token);
        SecurityContextHolder.setLoginUser(loginUser);
        log.info("loginUser:" + loginUser);
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.hasMethodAnnotation(RequireRole.class)) {
            RequireRole requireRole = handlerMethod.getMethodAnnotation(RequireRole.class);
            if (!Arrays.asList(requireRole.value()).contains(loginUser.getRole())) {
                throw new ShopManageException(ResultCodeEnum.PERMISSION.getMessage(),
                        ResultCodeEnum.PERMISSION.getCode());
            }
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception
    {
        log.info("remove");
        SecurityContextHolder.remove();
    }
}
